import React, { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, message, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import { getSchoolList, deleteSchool } from '@/services/school';
import SchoolForm from './components/SchoolForm';

const SchoolList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const [currentSchool, setCurrentSchool] = useState<API.School | undefined>(undefined);

  // 删除学校
  const handleDelete = async (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这所学校吗？此操作不可逆。',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const hide = message.loading('正在删除');
        try {
          await deleteSchool(id);
          hide();
          message.success('删除成功');
          actionRef.current?.reload();
        } catch (error) {
          hide();
          message.error('删除失败，请重试');
        }
      },
    });
  };

  // 查看详情
  const handleView = (record: API.School) => {
    history.push(`/school/detail/${record.id}`);
  };

  // 修改学校
  const handleUpdate = (record: API.School) => {
    setCurrentSchool(record);
    setUpdateModalVisible(true);
  };

  // 表格列配置
  const columns: ProColumns<API.School>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      copyable: true,
      ellipsis: true,
      width: 180,
    },
    {
      title: '学校名称',
      dataIndex: 'name',
      width: 180,
    },
    {
      title: '所属集团',
      dataIndex: 'groupName',
      width: 160,
    },
    {
      title: '所在区域',
      dataIndex: 'regionName',
      width: 100,
    },
    {
      title: '地址',
      dataIndex: 'address',
      ellipsis: true,
      width: 200,
    },
    {
      title: '网站',
      dataIndex: 'website',
      ellipsis: true,
      width: 180,
      render: (_, record) => (
        record.website ? (
          <a href={record.website} target="_blank" rel="noopener noreferrer">
            {record.website}
          </a>
        ) : '-'
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 180,
      valueType: 'dateTime',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      width: 180,
      valueType: 'dateTime',
    },
    {
      title: '操作',
      width: 180,
      valueType: 'option',
      render: (_, record) => [
        <a key="view" onClick={() => handleView(record)}>
          查看
        </a>,
        <a key="edit" style={{ marginLeft: 8 }} onClick={() => handleUpdate(record)}>
          编辑
        </a>,
        <a key="delete" style={{ marginLeft: 8, color: '#ff4d4f' }} onClick={() => handleDelete(record.id)}>
          删除
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.School, API.SchoolQueryParams>
        headerTitle="学校列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        toolBarRender={() => [
          <Button
            key="button"
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setCreateModalVisible(true)}
          >
            新建
          </Button>,
        ]}
        request={async (params) => {
          const { current, pageSize, ...rest } = params;
          const response = await getSchoolList({
            current,
            pageSize,
            ...rest,
          });
          return {
            data: response.data,
            success: response.success,
            total: response.total,
          };
        }}
        columns={columns}
        pagination={{
          pageSize: 10,
        }}
      />

      {/* 新建学校表单 */}
      <SchoolForm
        visible={createModalVisible}
        onCancel={() => setCreateModalVisible(false)}
        onSuccess={() => {
          setCreateModalVisible(false);
          actionRef.current?.reload();
        }}
      />

      {/* 编辑学校表单 */}
      {currentSchool && (
        <SchoolForm
          visible={updateModalVisible}
          values={currentSchool}
          onCancel={() => {
            setUpdateModalVisible(false);
            setCurrentSchool(undefined);
          }}
          onSuccess={() => {
            setUpdateModalVisible(false);
            setCurrentSchool(undefined);
            actionRef.current?.reload();
          }}
        />
      )}
    </PageContainer>
  );
};

export default SchoolList;
